package com.feng.demo.jakartacommons.mina;

import java.net.InetSocketAddress;

import org.apache.log4j.Logger;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LogLevel;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.feng.demo.jakartacommons.mina.codec.XMPPCodecFactory;

public class MinaClientTest {
	private static Logger logger = Logger.getLogger(MinaClientTest.class);
	public static void main(String[] args) {
		// 创建一个tcp/ip 连接
		IoConnector connector = new NioSocketConnector();
		// Set connect timeout.
		connector.setConnectTimeoutMillis(10* 1000);

		/*---------接收字符串---------*/
		// //创建接收数据的过滤器
		// DefaultIoFilterChainBuilder chain = connector.getFilterChain();
		// // 设定这个过滤器将一行一行(/r/n)的读取数据
		// chain.addLast("myChin", new ProtocolCodecFilter(
		// new TextLineCodecFactory()));
		/*---------接收对象---------*/
		// 创建接收数据的过滤器
		DefaultIoFilterChainBuilder chain = connector.getFilterChain();
		// 设定这个过滤器将以对象为单位读取数据
		// 设定服务器端的消息处理器:一个SamplMinaServerHandler对象,
		//chain.addLast("objectFilter", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
		//chain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"),LineDelimiter.WINDOWS.getValue(),LineDelimiter.WINDOWS.getValue())));
		chain.addLast("codec", new ProtocolCodecFilter(new XMPPCodecFactory()));
		LoggingFilter logFilter = new LoggingFilter();
		logFilter.setMessageReceivedLogLevel(LogLevel.DEBUG);
		logFilter.setMessageSentLogLevel(LogLevel.DEBUG);
		chain.addLast("logger", logFilter);
		// 设定服务器端的消息处理器:一个 SamplMinaServerHandler 对象,
		connector.setHandler(new ClientHanlder());
		// 连结到服务器:
		ConnectFuture cf = connector.connect(new InetSocketAddress("195.68.180.136", 19803));
		cf.awaitUninterruptibly();
		logger.info("Connection is ready!");
		/*IoSession session = cf.getSession();
		session.write("<h/>");*/
		
		// Wait for the connection attempt to be finished.
		cf.getSession().getCloseFuture().awaitUninterruptibly();
		connector.dispose();
	}
	
	public void clientStarter(){
		
	}
}
